<template>
  <div>
    <el-select
          v-model="id"
          filterable
          remote
          reserve-keyword
          placeholder="请输入关键词"
          :remote-method="getList"
          :loading="loading"
          :size="size"
          @change="selectList"
          style="width:100%">
          <el-option
            v-for="(item, index) in list"
            :key="index"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
  </div>
</template>

<script>
export default {
  props:{
    value:{
      type: Number | String,
    },
    api: {
      type: String,
    },
    options:{
      type: Object,
    },
    size: {
      type: String,
      default: () => 'small'
    },
  },
  data(){
    return{
      loading: false,
      opts:{
        id: 'id',
        name: 'name',
        searchKey: 'searchValue',
        data: 'data',
      },
      list: [],
    }
  },
  computed:{
    id:{
      get(){
        return this.value;
      },
      set(newVal){

      }
    },
  },
  created(){

  },
  methods:{
    getList(query) {
      if (query !== '') {
        this.loading = true;
        let options = Object.assign({}, this.opts, this.options);
        let params = {};
        params[this.options.searchKey] = query;
        setTimeout(() => {
          this.loading = false;
          this.$request('get', this.api, params, (data, msg) => {
            this.list = data[options.data].map(item=>{
              item.id=item[options.id];
              item.name=item[options.name];
              return item
            });
          });
        }, 200);
      } else {
        this.list = [];
      }
    },
    selectList(val){
      let obj = this.list.find(item => item.id == val);
      console.log(val,obj);
      this.$emit('confirm', obj);
      this.$emit('update:value', val);
    },
  }
}
</script>

<style>

</style>